
import { useLocation, useNavigate } from "react-router-dom";
import qs from 'query-string';
import React from "react";

/** 获取路由参数 */
export function useUrlParams<T = qs.ParsedQuery<string>>() {

    const navigate = useNavigate();

    const { search, state } = useLocation();

    const params = React.useMemo(() => qs.parse(search), [search]) as T

    const setParams = React.useCallback((ps: any, se?: any, replace = false) => {
        navigate(`.?${qs.stringify({ ...params, ...ps })}`, { state: { ...state, ...se }, replace })
    }, [params, state, navigate])

    return {
        /** 路由参数 */
        params,

        /** 数据 */
        state,

        /** 设置路由参数 */
        setParams,

        /** 路由跳转函数 */
        navigate,
    }
} 